﻿
#include <stdio.h>
#include <SL_tcpServer.h>
#include <thread>
#include <string>


class TestClient : public SLTcpClientCB
{
public:
    TestClient(const std::string s) : addr(s) {}
    virtual void TcpClient_onConnect(tcp_error_type _errType)
    {
        return;
    }
    virtual void TcpClient_onRecv(char* _pdata, int _len)
    {
        printf("addr : %s, recv_len : %d %s\n", addr.c_str(), _len, _pdata);
    }
    virtual void TcpClient_onSend()
    {
        return;
    }
    virtual void TcpClient_onError(tcp_error_type _type)
    {
        printf("addr : %s on error \n", addr.c_str());
    }

public:

    std::string addr;
};

class TestServer : public  SLTcpServerCB
{
public:
    virtual void TcpServer_onConnect(SLTcpClientPtr& _client)
    {
        printf("local addr : %d - %d \n", _client->getLocalAddr().m_ip, _client->getLocalAddr().m_port);
        printf("local addr : %d - %d \n", _client->getRemoteAddr().m_ip, _client->getRemoteAddr().m_port);

        _client->bindCB(SLTcpClientCBPtr(new TestClient(std::to_string(_client->getRemoteAddr().m_ip))));
    }

    virtual void TcpServer_onError()
    {
        printf("TcpServer_onError \n");
    }

private:
    std::vector<SLTcpClientPtr> m_client;
};

int tool_net_test_main()
{
    SLT_logInit();
    SLT_setLogLevel(1,1);
    SLT_setLogDisplay(1,1);
    SLT_setLogDisplaySync(1,1);


    //SLT_setLogConfig("ssss");
    SLTcpServerStpr tt = sl_createTcpServer();

    SLTcpServerCB* cbt = new TestServer();
    tt->init(cbt);
    tt->start();

    int uport = 30006;
    for (int i = 0; i < 2; ++i)
    {
        if (0 != tt->addListen("0.0.0.0", uport))
        {
            printf("add link fail");
            return -1;
        }
    
        if (0 != tt->delListen("0.0.0.0", uport))
        {
            printf("del link fail");
            return -1;
        }
    }
    uport = 0;
    tt->addListen("", uport);
    uport = 0;
    if (0 != tt->addListen("0.0.0.0", uport))
    {
        printf("add link fail");
        tt.reset();
        return 0;
    }
    else
    {
        printf("listen \n");
    }

    while (1)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        //printf("ssssssssssssss \n");
    }

	return 0;
}

